let isShowingLoginExpiredModal = false; // 标记登录过期弹窗是否已显示
const version = uni.getSystemInfoSync().version;
const baseUrl = "http://192.168.1.6:8088";
// 封装请求方法
const request = (options) => {
	return new Promise((resolve, reject) => {
		// 设置请求头，包含可能的 token
		const headers = {
			...options.header,
			Authorization: uni.getStorageSync("token") || "",
			version_no: version,
		};
		// 处理 GET 请求的参数拼接
		let url = baseUrl + options.url;
		if (options.method == "GET" && options.queryParams) {
			const queryString = Object.keys(options.queryParams)
				.map(
					(key) =>
					`${encodeURIComponent(key)}=${encodeURIComponent(
              options.queryParams[key]
            )}`
				)
				.join("&");
			if (queryString) {
				url += `?${queryString}`; // 确保拼接符号是 '?'
			}
		}
		uni.request({
			url: url,
			method: options.method || "GET",
			data: options.method === "GET" && options.queryParams ? {} : options.data || {},
			header: headers,
			success: (res) => {
				// 清除定时器并隐藏加载动画
				if (res.statusCode === 200) {
					let code = res.data.code;
					if (code === 401) {
						// 假设 401 是登录过期的状态码
						handleLoginExpired();
						reject("登录已过期，请重新登录");
					}
					if (code != 200) {
						showError(`请求失败：${res.data.msg}`);
						reject(`请求失败：${res.data}`);
					} else {
						resolve(res.data);
					}
				} else {
					showError(`请求失败	：${res.statusCode}`);
					reject(`请求失败：${res.statusCode}`);
				}
			},
		});
	});
};

// 显示错误提示
const showError = (message) => {
	uni.showToast({
		title: message,
		icon: "none",
		duration: 2000,
	});
};

// 处理登录过期
const handleLoginExpired = () => {
	if (!isShowingLoginExpiredModal) {
		isShowingLoginExpiredModal = true;
		uni.showModal({
			title: "提示",
			content: "登录已过期，请重新登录",
			showCancel: false,
			success: () => {
				isShowingLoginExpiredModal = false;
				// 这里可以添加重新跳转到登录页面的逻辑
				uni.reLaunch({
					url: "/pages/loginPage/loginPage",
				});
			},
		});
	}
};

export default request;